//
//  AppDelegate.m
//  XMPPDemo
//
//  Created by Edison on 16/1/14.
//  Copyright © 2016年 Gnet. All rights reserved.
//
#import "DEFINE.h"
#import "AppDelegate.h"
#import "LoginViewController.h"
#import "downloadCounter.h"
#import "GnetQM_XMPPManager.h"
#import "GnetQM_Server_CSCCheckVER.h"
//引导页
#import "GnetQM_introView.h"

@interface AppDelegate ()
@property (nonatomic, assign) BOOL newVersion;
@property (nonatomic, strong) GnetQM_introView *introView;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	
	// Override point for customization after application launch.
	UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil];
	[[UIApplication sharedApplication] registerUserNotificationSettings:notiSettings];
	
	[self loadWindowAndRootVC];
//	[self checkVersion];
	[self singleSignOn];


	return YES;
}


//加载跟控制器
- (void)loadWindowAndRootVC {
	[self judgeNewVersion];
	self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
	self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
	[self.window makeKeyAndVisible];
	[self loadIntroductionView];

	//发现应用已经更新
	if(self.newVersion) {
		//引导页是覆盖在rootViewController上面的
		[self loadIntroductionView];
		[self downloadCounting];
	}
	
}


- (void)applicationWillResignActive:(UIApplication *)application {
	// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
	// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
	// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
	// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
	// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
	[self checkVersion];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
	// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
	// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark- 单点登录
-(void)singleSignOn {
	if (nil != [[NSUserDefaults standardUserDefaults] objectForKey:kXMPPmyJID]) {
		//注册后 登录
		[[GnetQM_XMPPManager sharedInstance]registerMothod:^(BOOL ret) {
		}];
		
		//退出登录的回调  相关逻辑在此处处理
		[GnetQM_XMPPManager sharedInstance].loginOutBlock = ^(void) {
			NSLog(@"退出登录");
			[[NSUserDefaults standardUserDefaults] removeObjectForKey:kXMPPmyJID];
			[[NSUserDefaults standardUserDefaults] removeObjectForKey:kXMPPmyPassword];
			//退出登录
			// 1、向服务端发送退出指令
			// 2、退出登录
			//清空NSUserDefaults中的数据
			//清空角色
		};
	}
}

#pragma mark- 下载量统计
- (void)downloadCounting {
	//参数在downloadCounter.h中定义
	dispatch_async(dispatch_get_main_queue(), ^{
		[[downloadCounter sharedCounter] couting];
	});
	
}

#pragma mark- 引导页面
-(void)loadIntroductionView {
	[[GnetQM_introView sharedView] loadURLOrImages:k_Introduction_Parameter];
}

#pragma mark- 版本检测
- (void)judgeNewVersion {
	// 1. 取出当前版本
	NSString *currentVersion = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleShortVersionString"];
	// 2. 取出沙盒版本
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString *sandboxVersion = [defaults stringForKey:@"HistoryVersionKey"];
	
	_newVersion = [currentVersion compare:sandboxVersion] == NSOrderedDescending;
	// 3. 将当前版本保存至用户偏好(可以放在下载量统计中,统计成功再储存)
	[defaults setObject:currentVersion forKey:@"HistoryVersionKey"];
}

- (void)checkVersion {
	dispatch_async(dispatch_get_main_queue(), ^{
		GnetQM_Server_CSCCheckVER *tCheckVersion = [GnetQM_Server_CSCCheckVER shareSingleton];
		[tCheckVersion startCSCCheckVERCallBack:^(NSString *newVERUrl, NSString *newVERNum, NSString *newVERMsg, NSInteger newVERState) {
			NSLog(@"版本检测State:%zd",newVERState);
			if (1 == newVERState) {
				UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"发现新版本" message:newVERMsg preferredStyle:UIAlertControllerStyleActionSheet];
				// UIAlertControllerStyleActionSheet 显示在下面
				// UIAlertControllerStyleAlert 显示在中间
				UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"稍后" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
					//不点击按钮,点击周围的地方也会触发 UIAlertActionStyleCancel 这个按钮
					NSLog(@"点击了稍后按钮");
				}];
				UIAlertAction* action2 = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
					[[UIApplication sharedApplication] openURL:[NSURL URLWithString:newVERUrl]];
					exit(0);// 终止当前程序
				}];
				
				[alert addAction:action1];
				[alert addAction:action2];
				UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
				UIViewController *topVC = appRootVC;
				if (topVC.presentedViewController) {
					topVC = topVC.presentedViewController;
				}
				[topVC presentViewController:alert animated:YES completion:nil];
			}
		}];
	});
}

@end
